package com.lengyue.imakiba.manage;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.lengyue.imakiba.base.FileTools;
import com.lengyue.imakiba.data.Anime;
import com.lengyue.imakiba.data.AnimeInterface;
import com.lengyue.imakiba.data.AnimeType;
import com.lengyue.imakiba.data.Dict;
import com.lengyue.imakiba.data.Type;

public class AnimeManage  extends Controller implements AnimeInterface{
	public void getAnimes()
	{
		String code = (getPara("code")==null?"":getPara("code")).trim();
		String name = (getPara("name")==null?"":getPara("name")).trim();
		Page<Anime> animesPages = Anime.dao.paginate(getParaToInt("page"), getParaToInt("rows"), "select DISTINCT a.*","from anime a left join episode e on e.anime_id = a.id where a.code like CONCAT('%',?,'%') and a.name like CONCAT('%',?,'%') order by e.date desc",code,name);
		List<Anime> animes = animesPages.getList();
		//查询关联的动漫类型
		for(Anime a : animes)
		{
			List<Type> types = a.getType();
			for(Type type : types)
			{
				type.put("type_name", getText(type.getStr("type_code")));
			}
			a.put("type", types);
		}
		long total = Anime.dao.find("select count(id) total from anime").get(0).getLong("total");
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", total);
		jsonMap.put("rows", animes);
		renderJson(jsonMap);
	}
	public void getAnime()
	{
		Anime anime = new Anime();
		if(getPara("animeId")!=null)
		{
			int animeId = getParaToInt("animeId");
			anime = Anime.dao.findById(animeId);
			//转换描述用于CKEDITOR设置初始值
			if(anime.getStr("description")!=null)
			{
				anime.set("description", anime.getStr("description").replace("\r\n", "\\\n"));
			}
			anime.put("type", anime.getType());
		}
		List<Type> types = Type.dao.find("select * from type");
		List<Dict> states = new DictManage().getDictByDictType("state", "asc");
		setAttr("anime", anime);
		setAttr("types", types);
		setAttr("states", states);
		setAttr("coverPath", coverPath);
		render("/WEB-INF/freeMarkerTemplete/anime_edit.ftl");
	}
	public void saveAnime()
	{
		if(getPara("id")==null||getPara("id")=="")
		{
			addAnime();
		}
		else
		{
			updateAnime();
		}
	}
	@Before(Tx.class)
	public void addAnime()
	{
		Anime anime = new Anime().set("code", getPara("code")).set("name", getPara("name"))
		.set("description", getPara("description")).set("cover_url", getPara("cover_url")).set("baike_url", getPara("baike_url")).set("state", getPara("state"));
		anime.save();
		saveAnimeType(anime.getInt("id"), getParaValues("type"));
		String[] cvs = getParaValues("cv");
		AnimeCVManage.updateCVByAnime(anime.getInt("id"), cvs);
		//返回动漫
		renderJson(anime);
	}
	@Before(Tx.class)
	public void updateAnime()
	{
		Anime anime =new Anime().set("id", getPara("id")).set("code", getPara("code")).set("name", getPara("name"))
		.set("description", getPara("description")).set("cover_url", getPara("cover_url")).set("baike_url", getPara("baike_url")).set("state", getPara("state"));
		anime.update();
		String[] cvs = getParaValues("cv");
		int animeId = Integer.parseInt(anime.getStr("id"));
		AnimeCVManage.updateCVByAnime(animeId, cvs);
		deleteAnimeTypeByAnimeId(animeId);
		saveAnimeType(animeId, getParaValues("type"));
		//返回动漫
		renderJson(anime);
	}
	@Before(Tx.class)
	public void deleteAnime()
	{
		deleteAnimeTypeByAnimeId(getParaToInt("animeId"));
		deleteEpisodeByAnimeId(getParaToInt("animeId"));
		AnimeCVManage.deleteCVByAnime(getParaToInt("animeId"));
		Anime anime = Anime.dao.findById(getParaToInt("animeId"));
		deleteCover(anime.getStr("cover_url"));
		Anime.dao.deleteById(getParaToInt("animeId"));
		renderNull();
	}
	private void saveAnimeType(int AnimeId,String[] types)
	{
		for(String type : types)
		{
			new AnimeType().set("anime_id", AnimeId).set("type_code", type).save();
		}
	}
	/**
	 * 删除动漫对应的动漫-类型关系
	 * @param animeId 动漫Id
	 */
	private void deleteAnimeTypeByAnimeId(int animeId)
	{
		Db.update("delete from anime_type where anime_id = ?", animeId);
	}
	/**
	 * 删除动漫的剧集
	 * @param animeId 动漫Id
	 */
	private void deleteEpisodeByAnimeId(int animeId)
	{
		Db.update("delete from episode where anime_id = ?", animeId);
	}
	/**
	 * 删除上传路径下指定的封面
	 * @param cover 封面文件名
	 */
	private void deleteCover(String cover)
	{
		String path = getSession().getServletContext().getRealPath(coverPath+cover);
		File f = new File(path);
		if(f.exists()&&f.isFile())
		{
			f.delete();
		}
	}
	public void changeCover()
	{
		UploadFile file = getFile();
		//cover有值就删除对应的文件，没值则只新增文件
		String cover = getPara("cover");
		//有animeId则上传文件后更新animeId对应的cover_url
		String animeId = getPara("animeId");
		String realPath = getSession().getServletContext().getRealPath("/");
		if(cover!=null&&!"noCover.jpg".equals(cover))
		{
			File oldCover = new File(realPath+coverPath+cover);
			if(oldCover.exists()&&oldCover.isFile())
			{
				oldCover.delete();
			}
		}
		//移动封面文件到封面文件夹
		FileTools.moveFile(file.getFile(),realPath,coverPath, null);
		if(animeId!=null)
		{
			Anime.dao.findById(Integer.parseInt(animeId)).set("cover_url", file.getFileName()).update();
		}
		renderText(file.getFileName());
	}
}
